﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using System.Transactions;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Action.SPI;
using T.ServiceComponent.DAC.Service;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.Action.Dao
{
    public class DataBaseInfoDao : DaoService<DataBaseInfo>
    {
        public const string MetaDataID = "fas_database";
        public const string MetaDataName = "数据库连接信息";
        public override string TableName => "fas_database";
        public override string IDColumnName => "ID";

        public override Dictionary<string, object> GetDataMapping(DataBaseInfo data)
        {
            var mapping = base.GetDataMapping(data);
            return mapping;
        }
        public DataBaseInfoDao() : base()
        {
            DBName = "TFAS";
        }
        public override Dictionary<string, PropertyInfo> GetColumns()
        {
            return DaoServiceExtension.GetAllColumns<DataBaseInfo>(base.GetColumns());
        }
        public DataBaseInfo GetDefaultDataBaseInfoById(string databaseID)
        {
            if (string.IsNullOrEmpty(databaseID))
                return null;
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            var sql = @"select b.id as ID,b.Code as Code,b.dbType as DBType,c.configkey as ConfigKey from fas_databaseconfig c left join fas_database b on b.id = c.databaseid where c.isdefault = 1 and c.databaseid =@databaseid";
            paramsList.Add(DB.MakeInParam("@databaseid", TDbDataType.VarChar, databaseID));
            var dataResult = DB.ExecuteDataSet(sql, paramsList.ToArray());
            var result =  DataResultConvert.ConvertToDataBaseInfo(dataResult);
            if (result == null || result.Count <= 0)
                return null;
            return result[0];
        }
        public DataBaseInfo GetDefaultDataBaseInfoByCode(string databaseCode)
        {
            if (string.IsNullOrEmpty(databaseCode))
                return null;
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            var sql = @"select b.id as ID,b.Code as Code,b.dbType as DBType,c.configkey as ConfigKey from fas_databaseconfig c left join fas_database b on b.id = c.databaseid where c.isdefault = 1 and b.Code =@databaseCode";
            paramsList.Add(DB.MakeInParam("@databaseCode", TDbDataType.VarChar, databaseCode));
            var dataResult = DB.ExecuteDataSet(sql, paramsList.ToArray());
            var result = DataResultConvert.ConvertToDataBaseInfo(dataResult);
            if (result == null || result.Count <= 0)
                return null;
            return result[0];
        }
    }
}
